import "@/styles/instruction.less";
/**
 *@tip 自定义指令集合
 */

/**
 *@name 显示更多  当一段文字过长时候，可以先在一行内显示一部分，点击显示全部
 *@tip 本指令与 :class 有强烈的不兼容性
 *@tip 用法 <div v-showmore="true"><span class="text">需要显示的文字</span></div>
 */
function showmore() {
  function setClassName(currentDom: any) {
    const enable = currentDom.dataset.enable == "true";
    let className = currentDom.className || "";
    const isHide = className.includes("publice-text-show-more-hide");
    className = className.replaceAll("publice-text-show-more-box", "");
    className = className.replaceAll("publice-text-show-more-hide", "");
    if (enable) {
      className += " publice-text-show-more-box";
      if (!isHide) {
        className += " publice-text-show-more-hide";
      }
    }
    className = className.replaceAll(/\s+/g, " ");
    currentDom.className = className;
  }
  function clickFn(e: any) {
    setClassName(e.currentTarget);
  }

  return {
    // 当被绑定的元素插入到 DOM 中时……
    mounted(el: any, val: any) {
      el.dataset.enable = !val.value;

      el.addEventListener("click", clickFn);
      if (el.dataset.enable) {
        setClassName(el);
      }
    },
    beforeUpdate(el: any, val: any) {
      el.dataset.enable = !val.value;
      //   当是否启用发生了变化后，
      console.log(val.value,val.oldValue);
      
      if (el.dataset.enable !== val.oldValue && val.oldValue !== undefined) {
        setClassName(el);
      }
    },
    beforeUnmount(el: any) {
      el.removeEventListener("click", clickFn);
    },
  };
}
/**
 *@name 所有的自定义指令集合
 */
const allInstruction: AnyObj = { showmore };
export default function (app: any) {
  // 注册一个全局自定义指令 `v-focus`
  for (let key in allInstruction) {
    app.directive(key, allInstruction[key]());
  }
}
